/**
 * Program 12.3 Key-indexed-array–based symbol table
 * ---------------------------------------------------------------------------
 * This code assumes that key values are positive integers less than `maxKey` (which is defined in `Item.h`).
 *
 * The primary factors limiting its applicability are the amount of space required when `maxKey` is large, and
 * the amount of time required for `STinit` when `N` is small relative to maxKey.
 *
 * Compilation of this code as a separate module requires include directives for `<stdlib.h>`, `"Item.h"`, and `"ST.h"`.
 * We omit these lines of code in this and other symbol-table implementations.
 *
 */

#include <stdlib.h>
#include "Item.h"
#include "ST.h"

static Item *st;

static int M = maxKey;

void STinit(int maxN) {
    int i;
    st = malloc((M+1)*sizeof(Item));
    for (i = 0; i <= M; i++) {
        st[i] = NULLitem;
    }
}

int STcount() {
    int i, N;
    for (i = 0, N = 0; i < M; i++) {
        if (st[i] != NULLitem) {
            N++;
        }
    }
    return N;
}

void STinsert(Item item) {
    st[key(item)] = item;
}

Item STsearch(Key v) {
    return st[v];
}

void STdelete(Item item) {
    st[key(item)] = NULLitem;
}

Item STselect(int k) {
    int i;
    for (i = 0; i < M; i++) {
        if (st[i] != NULLitem) {
            if (k-- == 0) {
                return st[i];
            }
        }
    }
    return NULLitem;
}

void STsort(void (*visit)(Item)) {
    int i;
    for (i = 0; i < M; i++) {
        if (st[i] != NULLitem) {
            visit(st[i]);
        }
    }
}







